package com.generator.helper;

import com.generator.config.BaseConfiguration;
import com.generator.domain.ColumnDO;
import com.generator.domain.TableDO;
import com.generator.utils.DBUtil;
import com.google.common.collect.Lists;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

/**
 * 〈 help to  assume tableDO  and ColumnDO〉
 *
 * @author xsh
 * @create 2018/9/17
 * @since 1.0.0
 */
@Component
public class TableHelper {

    @Autowired
    DBUtil dbUtil ;

    @Autowired
    BaseConfiguration configuration;

    Configuration dateTypeConfiguration = getConfig();


    public TableDO buildTable(String tableName) {
        try {
            Connection connection = dbUtil.getConnection();

            String sql = " select table_name tableName, engine, table_comment tableComment, create_time createTime from INFORMATION_SCHEMA.TABLES   where table_schema = (select database()) and table_name ='" + tableName+"'";

            PreparedStatement statement = dbUtil.getStatement(connection, sql);

            ResultSet resultSet = statement.executeQuery();

            TableDO tableDO = new TableDO();

            while (resultSet.next()) {
                tableDO.setTableName(resultSet.getString("tableName"));
                tableDO.setComment(resultSet.getString("tableComment"));
                resultSet.getString("createTime");
                resultSet.getString("engine");
                String  className =  getTableName(resultSet.getString("tableName"));
                tableDO.setClassName(className);
                tableDO.setClassname(StringUtils.uncapitalize(className));
            }

            return tableDO;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    public List<ColumnDO> buildColumns(String tableName,TableDO tableDO) {
        try {

            Connection connection = dbUtil.getConnection();

            String sql = " select COLUMN_NAME columnName  ,column_comment columnComment , data_type dataType , column_comment   columnComment, column_key    columnKey, extra from INFORMATION_SCHEMA.Columns where table_name= '" + tableName+"'";

            PreparedStatement statement = dbUtil.getStatement(connection, sql);

            ResultSet resultSet = statement.executeQuery();

            List<ColumnDO>  columnDOS  = Lists.newArrayList();

            while (resultSet.next()){
                ColumnDO columnDO =  new ColumnDO();
                String columnName = resultSet.getString("columnName");
                columnDO.setColumnName(columnName);
                columnDO.setComment(resultSet.getString("columnComment"));
                columnDO.setAttrName(columnToJava(columnName));
                columnDO.setAttrname(StringUtils.uncapitalize(columnToJava(columnName)));
                String dataType = resultSet.getString("dataType");
                columnDO.setDataType(dataType);
                if ("BigDecimal".equals(dataType)){
                    tableDO.setHasBigDecimal("true");
                }
                columnDO.setExtra(resultSet.getString("extra"));
                columnDO.setAttrType(dateTypeConfiguration.getString(dataType));
                //是否主键
                if ("PRI".equalsIgnoreCase(resultSet.getString("columnKey")) && tableDO.getPk() == null) {
                    tableDO.setPk(columnDO);
                }
                columnDOS.add(columnDO);
            }
            return columnDOS;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    private String getTableName(String tableName) {

        String tablePrefix = configuration.getTablePrefix();

        if (configuration.isAutoRemovePre()) {
            tableName = tableName.substring(tableName.indexOf("_") + 1);
        }
        if (StringUtils.isNotBlank(configuration.getTablePrefix())) {
            tableName = tableName.replace(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 列名转换成Java属性名
     */
    private  String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }


    public    static Configuration getConfig(){
        try {
            return new PropertiesConfiguration("dataType.properties");
        } catch (ConfigurationException e) {
            throw new RuntimeException("获取配置文件失败，", e);
        }
    }

}